package controller;

import com.alibaba.fastjson.JSON;
import entity.User;
import utils.XBHashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;


public class BaseServlet extends HttpServlet {

    public User loginUser;


    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        loginUser = (User) session.getAttribute("loginUser");


        try {
                String requestURI = req.getRequestURI();
                //targetName:login
                String tragetName = requestURI.substring(requestURI.lastIndexOf('/') + 1);
                //获取目标资源的那个类的字节码对象（user）
                Class<? extends BaseServlet> tragetClass = this.getClass();
                //反射这个方法
                Method method = tragetClass.getDeclaredMethod(tragetName, HttpServletRequest.class, HttpServletResponse.class);

                //开启强制访问
                method.setAccessible(true);

                //执行这个方法
                method.invoke(this,req,resp);

            }catch (Exception e) {
                throw new RuntimeException(e);

        }

    }
    public static Map<String,String> getParam(HttpServletRequest req) {

        Map<String,String>returnMap = new XBHashMap();

        Map<String, String[]> parameterMap = req.getParameterMap();

        for (String key : parameterMap.keySet()) {
            String[] values = parameterMap.get(key);
            if (values.length > 1) {

                // 使用逗号拼接字符串 [3,4,5,6,7]
                String val = Arrays.toString(values);

                returnMap.put(key, val);
            } else {
            returnMap.put(key, values[0]);
        }

    }
        return returnMap;
    }

    public void writerObjToString(HttpServletResponse response,Object object) {
        try {
            String jsonStr = JSON.toJSONString(object);

            response.setContentType("application/json;charset=utf8");

            response.getWriter().write(jsonStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
